<template>
  <view class="history content-wrap">
    <u-navbar title="实时曲线" :title-bold="true" back-icon-color="#333" title-color="#000">
      <view slot="right" class="navbar-right">
        <image src="/static/image/screen.svg" @click="clickBtn" class="navbar-right--icon" />
      </view>
    </u-navbar>
    <view class="search">
      <u-search
        placeholder="请输入传感器名称"
        v-model="searchData.cdLocation"
        shape="square"
        bg-color="#E5EAE8"
        height="80"
        :show-action="true"
        :input-style="{ marginLeft: '20rpx' }"
        :search-icon="searchSrc"
        placeholder-color="#999999"
        :disabled="true"
        :action-style="{
          color: '#369164',
          fontSize: '14px',
          fontWeight: '400',
        }"
        @custom="searchChart"
        @click="openSensor"
      ></u-search>
    </view>

    <view class="charts-box u-flex-1" :key="reshow">
      <qiun-data-charts
        v-if="!showechartEmpty"
        type="line"
        :echartsH5="true"
        :echartsApp="true"
        :eopts="eopts"
        :reshow="reshow"
        tooltipFormat="tooltipDemo1"
        :chartData="chartData"
      />
      <div v-if="!showTitle" class="chart-title">
        <div class="flex">
          <div class="u-flex">
            <div class="warn-box m-r-10"></div>
            <span class="f-12">报警</span>
          </div>
          <div class="m-l-10 u-flex">
            <div class="calibration-box m-r-10"></div>
            <span class="f-12">标校</span>
          </div>
        </div>
      </div>
      <div v-if="!showTitle" class="f-14 chart-sub-title">监测值</div>
      <template v-if="showechartEmpty">
        <view class="c-empty p-absolute-center">
          <u-empty text="暂无数据"></u-empty>
        </view>
      </template>
    </view>

    <u-popup mode="bottom" v-model="show">
      <view class="popup-content">
        <view class="u-flex u-row-between u-p-b-20">
          <u-button :hair-line="false" :custom-style="customStyle" throttle-time="500" @click="cancelSensor">取消</u-button>
          <u-button :hair-line="false" :custom-style="submitStyle" throttle-time="500" @click="clickSensor">确定</u-button>
        </view>
        <view class="u-p-b-20">
          <u-search
            placeholder="请输入传感器名称"
            v-model="filtersensorTypesVal"
            shape="square"
            bg-color="#E5EAE8"
            height="80"
            :show-action="true"
            :animation="true"
            :input-style="{ marginLeft: '20rpx' }"
            :search-icon="searchSrc"
            placeholder-color="#999999"
            :action-style="{
              color: '#369164',
              fontSize: '14px',
              fontWeight: '400',
            }"
          ></u-search>
        </view>
        <scroll-view scroll-y="true" style="height: 600rpx">
          <view class="w-100p checkbox">
            <u-checkbox-group active-color="#9AC8B1" width="100%" :wrap="true">
              <u-checkbox
                @change="checkboxsensorTypesChange"
                v-model="item.checked"
                class="checkbox-item"
                v-for="(item, index) in filtersensorTypesList"
                :key="index"
                :name="item.name"
                :disabled="item.disabled"
              >{{ item.name }}</u-checkbox>
            </u-checkbox-group>
            <template v-if="filtersensorTypesList && filtersensorTypesList.length === 0">
              <view class="c-empty p-absolute-center">
                <u-empty text="暂无数据"></u-empty>
              </view>
            </template>
          </view>
        </scroll-view>
      </view>
    </u-popup>
    <u-toast ref="uToast" />
  </view>
</template>

<script>
export default {
  data() {
    return {
      tooltipCustom: {
        textList: []
      },
      form: {
        sensorName: '', // 传感器类型名称
        sensorType: [] // 传感器类型
      },
      coalMineName: '',
      customerNo: '', //煤矿编码
      cdCodes: [], //测点编码
      eopts: {},
      data: {},
      searchData: {
        cdLocation: '', // 测点安装位置
        cdCodes: [], //传感器类型编码列表
        customerNo: '', //煤矿编码
        enableAddPoint: false,
        sensorType: '', //传感器类型
        unitCode: '', //单位
        cdCode: ''
      },
      arr: [],
      arrTwo: [],
      arrThree: [],
      cdLocation: '', // 传感器名称
      unitCode: '',
      sensorTypes: [], //获取传感器名称的搜索条件
      sensorTypesList: [],
      filtersensorTypesVal: '', //传感器名称搜索数据
      show: false,
      customStyle: {
        // 注意驼峰命名，并且值必须用引号包括，因为这是对象
        color: '#333333',
        background: '#F1F5F3',
        borderRadius: '20rpx',
        width: '40%',
        border: 'none'
      },
      submitStyle: {
        color: '#333333',
        background: '#5BAC84',
        borderRadius: '20rpx',
        width: '40%',
        border: 'none'
      },
      color: [
        '#0EECF1',
        '#ffff00',
        '#ffa500',
        '#0000FF',
        '#C43CC4',
        '#9400d3',
        '#9f79ee',
        '#696969',
        '#ff00ff',
        '#bdb76b',
        '#006400',
        '#00bfff',
        '#66cd00',
        '#8b8989',
        '#ff1493'
      ],
      checkList: [],
      searchSrc: require('@/static/image/search_icon.svg'),
      eChartDataCache: [],
      showechartEmpty: false,
      showTitle: true,
      chartData: {
        categories: [],
        series: []
      },
      isGetSensorList: true,
      reshow: false
    }
  },
  mounted() {
    // await this.getData();
    this.interval = setInterval(() => {
      this.pushData()
    }, 5000)
  },
  beforeDestroy() {
    clearInterval(this.interval)
  },
  computed: {
    filtersensorTypesList() {
      return this.sensorTypesList?.filter(item => {
        return this.filtersensorTypesVal
          ? item.name?.indexOf(this.filtersensorTypesVal) >= 0 || item.pinyin_code?.indexOf(this.filtersensorTypesVal.toUpperCase()) >= 0
          : true
      })
    }
  },
  methods: {
    /**
     * 初始化
     */
    init(data) {
      let { cdCode, cd_location, areaLocation, customerNo, sensorType, unitCode } = data
      if (data) {
        this.searchData.cdCodes.push(cdCode)
        this.searchData.cdCode = cdCode
        this.searchData.cdLocation = cd_location ? cd_location : areaLocation
        this.searchData.customerNo = customerNo
        this.searchData.sensorType = sensorType
        this.searchData.unitCode = unitCode
      }
    },
    setOpts() {
      this.eopts = {
        title: {
          text: '',
          textAlign: 'center',
          top: '50%',
          right: '-5%',
          rotate: -90
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            yAxisIndex: [0],
            start: 0,
            end: 100,
            top: '60',
            showDetail: false,
            left: '0%'
          }
        ],
        legend: {
          rotation: -90,
          left: '10%',
          top: 'center',
          orient: 'vertical'
        },
        graphic: [],
        grid: {
          left: '30%',
          right: '70',
          top: '60'
        },
        tooltip: {
          show: true,
          backgroundColor: '#ffffff',
          trigger: 'axis',
          triggerOn: 'mousemove',
          borderColor: '#369164',
          borderWidth: 1,
          padding: [5, 10],
          extraCssText: 'box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);Opacity: 1;z-index:999;transform: rotate(90deg);',
          textStyle: {
            color: '#666666'
          }
        },
        xAxis: {
          type: 'value', //数据
          position: 'top', //x 轴的位置【top bottom】
          nameRotate: -90, //坐标轴名字旋转，角度值。
          axisLabel: {
            //坐标轴刻度标签的相关设置。
            rotate: 90 //刻度标签旋转的角度，
          }
          // scale: true, //是否是脱离 0 值比例
        },
        yAxis: {
          // max: function (val) {
          //   return val.max < 1 ? 1 : val.max
          // },
          axisLine: {
            lineStyle: {
              color: '#666666'
            }
          },
          type: 'category',
          inverse: 'true', //是否是反向坐标轴。
          axisLabel: { rotate: -90 }
        },
        visualMap: [],
        series: []
      }
      this.eopts.title.text = this.$isNull(this.data.customerShortName)
        ? this.coalMineName + '传感器实时曲线图'
        : this.data.customerShortName + '传感器实时曲线图'
    },
    setText() {
      this.tooltipCustom.textList = []
      let length = this.chartData.series.length
      let num = 0
      num = Number(length) * 3
      for (let i = 0; i < num; i++) {
        this.tooltipCustom.textList.push({ text: '0' })
      }
    },
    openSensor() {
      this.show = true
      this.initSensor()
    },
    // 传感器类型数据初始化
    initSensor() {
      if (this.searchData.cdCodes !== []) {
        this.arr = []
        this.arrTwo = []
        this.arrThree = []
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          if (this.searchData.cdCodes.includes(`${this.sensorTypesList[i].cdCode}`)) {
            this.arr.push(this.sensorTypesList[i].cdLocation)
            this.arrTwo.push(this.sensorTypesList[i].cdCode)
            if (this.sensorTypesList[i].unitCode && this.searchData.unitCode.indexOf(this.sensorTypesList[i].unitCode) === -1) {
              this.arrThree.push(this.sensorTypesList[i].unitCode)
            }
            this.$set(this.sensorTypesList[i], 'checked', true)
          } else {
            this.$set(this.sensorTypesList[i], 'checked', false)
          }
        }
        this.$set(this, 'cdCodes', this.arrTwo)
        this.$set(this, 'unitCode', this.arrThree.toString())
        this.$set(this, 'cdLocation', this.arr.toString())
      } else {
        this.arr = []
        this.arrTwo = []
        this.arrThree = []
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          this.$set(this.sensorTypesList[i], 'disabled', false)
          this.$set(this.sensorTypesList[i], 'checked', false)
        }
        this.cdCodes = []
        this.cdLocation = ''
        this.unitCode = ''
      }
    },
    // 传感器类型数据取消
    cancelSensor() {
      this.initSensor()
      this.show = false
      this.filtersensorTypesVal = ''
    },
    // 传感器类型数据确认
    clickSensor() {
      this.searchData.cdCodes = this.cdCodes
      this.searchData.cdLocation = this.cdLocation
      this.searchData.unitCode = this.unitCode
      this.filtersensorTypesVal = ''
      this.show = false
      this.reshow = false
      if (!this.searchData.cdCodes.length) {
        this.showTitle = true
        this.showechartEmpty = true
        this.$refs.uToast.show({
          title: '请选择传感器',
          type: 'warning'
        })
      } else {
        this.showechartEmpty = false
      }
      this.searchChart()
      this.setText()
    },
    // 选中sensorType某个复选框时，由checkbox时触发
    checkboxsensorTypesChange(e) {
      if (e.value === true) {
        this.arr.push(e.name)
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          if (this.sensorTypesList[i].cdLocation === e.name) {
            this.arrTwo.push(this.sensorTypesList[i].cdCode)
            if (this.sensorTypesList[i].unitCode && this.searchData?.unitCode.indexOf(this.sensorTypesList[i]?.unitCode) === -1) {
              this.arrThree.push(this.sensorTypesList[i].unitCode)
            }
          }
        }
      } else {
        this.deleteOne(e.name, this.arr)
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          if (this.sensorTypesList[i].cdLocation === e.name) {
            this.deleteOne(this.sensorTypesList[i].cdCode, this.arrTwo)
            this.deleteOne(this.sensorTypesList[i].unitCode, this.arrThree)
          }
        }
      }
      let checked = []
      if (this.arrTwo.length === 4) {
        checked = this.arrTwo
        this.$refs.uToast.show({
          title: '传感器名称最多只能选择四个',
          type: 'warning'
        })
      }
      if (this.arrTwo.length >= 4) {
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          if (checked.includes(this.sensorTypesList[i].cdCode)) {
            this.$set(this.sensorTypesList[i], 'disabled', false)
          } else {
            this.$set(this.sensorTypesList[i], 'disabled', true)
          }
        }
      } else {
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          this.$set(this.sensorTypesList[i], 'disabled', false)
        }
      }
      this.cdCodes = this.arrTwo
      this.cdLocation = this.arr.toString()
      this.unitCode = this.arrThree.toString()
    },
    //删除数组元素
    deleteOne(str, arr) {
      let index = arr.indexOf(str)
      arr.splice(index, 1)
      return arr
    },
    //echarts图数据搜索
    searchChart() {
      if (this.searchData.cdCodes.length) {
        // 取消了某个传感器 删除他
        if (this.searchData.cdCodes.length < this.eChartDataCache.length) {
          for (let i = this.eChartDataCache.length - 1; i >= 0; i--) {
            let item = this.eChartDataCache[i]
            if (!this.searchData.cdCodes.includes(item.cdCode)) {
              this.eChartDataCache.splice(i, 1)
            }
          }
        }
        this.showEChartData()
      } else {
        this.clearECharts()
      }
    },
    //清除echart数据
    clearECharts() {
      this.chartData.categories = []
      this.chartData.series = []
    },
    //展现echart数据
    showEChartData() {
      this.clearECharts()
      for (let i = 0; i < this.eChartDataCache?.length; i++) {
        // 获取传感器
        let sensor = this.eChartDataCache[i]
        // 开关的特殊处理
        let step = false
        if (sensor.sensorType && sensor.sensorType.substr(0, 1) !== '0') {
          step = 'start'
        }

        this.chartData.series[i] = {
          type: 'line',
          name: sensor.cdLocation,
          data: [],
          label: { rotate: -90, show: false },
          lineStyle: {
            color: sensor.color,
            width: 3
          },
          itemStyle: {
            color: sensor.color
          },
          step
        }

        // 获取传感器数据
        let sensorData = sensor.data

        // 构建 X 轴，只需执行一次
        if (i === 0) {
          this.chartData.categories = sensorData.map(item => item.dateMinute)
        }

        const isAdd = this.chartData.categories.length - sensorData.length
        if (isAdd > 0) {
          for (let x = 0; x < isAdd; x++) {
            this.chartData.series[i].data.push({
              value: null
            })
          }
        }

        for (let i2 = 0; i2 < sensorData.length; i2++) {
          // 获取传感器明细
          let sensorDetial = sensorData[i2]

          this.chartData.series[i].data.push({
            value: sensorDetial.cdValue,
            dateMinute: sensorDetial.dateMinute,
            unitCode: sensorDetial.unitCode
          })
        }
      }
      if (this.chartData.categories.length > 0) {
        this.showechartEmpty = false
        this.showTitle = false
      } else {
        this.showechartEmpty = true
        this.showTitle = true
      }
      this.setText()
    },
    // 获取传感器列表
    async getName() {
      let params = {
        customerNo: this.customerNo, //煤矿编码
        cdCode: this.cdCodes.toString(), //测点编码
        sensorTypes: this.sensorTypes ? this.sensorTypes : [] //传感器类型列表
      }
      const res = await this.$form('/alarm/fusionAnalysis/getHisGraphSensorList', params)
      if (res) {
        this.sensorTypesList = res.body
        for (let i = 0; i < this.sensorTypesList?.length; i++) {
          this.$set(this.sensorTypesList[i], 'disabled', false)
          this.$set(this.sensorTypesList[i], 'checked', false)
          this.$set(this.sensorTypesList[i], 'name', this.sensorTypesList[i].cdLocation)
        }
      }
    },
    //实时加载数据
    pushData() {
      if (!this.searchData.cdCodes.length) {
        this.showTitle = true
        this.showechartEmpty = true
        this.$refs.uToast.show({
          title: '请选择传感器',
          type: 'warning'
        })
        return
      }
      this.$form('/alarm/fusionAnalysis/getHistoryRealTimePushCurve', {
        customerNo: this.customerNo, //煤矿编码
        cdCodes: this.searchData.cdCodes
      }).then(data => {
        data = data.body.data
        this.reshow = true
        if (data.length > 0) {
          data.forEach(cd => {
            let hasCache = this.eChartDataCache.find(item => cd.cd_code === item.cdCode)
            if (hasCache) {
              hasCache.data.push({
                cdLocation: cd.cd_location == null ? this.getCdName(cd.cd_code) : cd.cd_location,
                cdValue: cd.cd_value == null ? '-' : cd.cd_value,
                dateMinute: cd.record_date,
                sensorType: cd.sensor_type_no,
                cdCode: cd.cd_code
              })
            } else {
              this.eChartDataCache.push({
                cdCode: cd.cd_code,
                cdLocation: cd.cd_location == null ? this.getCdName(cd.cd_code) : cd.cd_location,
                color: this.color[this.colorIndex],
                data: [
                  {
                    cdLocation: cd.cd_location == null ? this.getCdName(cd.cd_code) : cd.cd_location,
                    cdValue: cd.cd_value == null ? '-' : cd.cd_value,
                    dateMinute: cd.record_date,
                    sensorType: cd.sensor_type_no,
                    cdCode: cd.cd_code
                  }
                ],
                sensorType: cd.sensor_type_no
              })
              this.colorIndex++
            }
          })
        }
        if (this.eChartDataCache.length > 0) {
          this.showEChartData()
        }
      })
    },
    // 返回传感器名称
    getCdName(cdCode) {
      let name = ''
      this.sensorTypesList.forEach(item => {
        if (cdCode === item.cdCode) {
          name = item.cdLocation
          return name
        }
      })
      return name
    },
    clickBtn() {
      uni.navigateTo({
        url: `./realTimeScreen?customerNo=${this.customerNo}&cdCode=${this.cdCodes.toString()}&sensorType=${
          this.data.sensorType
        }&form=${JSON.stringify(this.form)}&data=${JSON.stringify(this.searchData)}`
      })
    },
    //点击搜索后重置搜索条件
    initSearchData(res) {
      this.eChartDataCache = []
      this.$set(this, 'sensorTypes', res.sensorType)
      this.$set(this.searchData, 'cdLocation', '')
      this.$set(this.searchData, 'unitCode', '')
      this.$set(this.searchData, 'cdCodes', [])
      this.$set(this.searchData, 'sensorType', res.sensorType.toString())
      this.cdLocation = ''
      this.unitCode = ''
      this.cdCodes = []
      this.arr = []
      this.arrTwo = []
    }
  },
  onLoad(options) {
    const { data, coalMineName } = options
    this.coalMineName = coalMineName
    this.data = JSON.parse(data)
    this.form.sensorType = this.data.sensorType.split(',')
    this.form.sensorName = this.data.sensorTypeName
    this.sensorTypes.push(this.data.sensorType)
    this.customerNo = this.data.customerNo
    this.cdCodes.push(this.data.cdCode)
    this.unitCode = this.data.unitCode
    this.init(this.data)
    this.setOpts()

    uni.$on('handClickrealTimeScreen', res => {
      this.form = res
      this.showTitle = false
      if (res.sensorType.length !== 0 || res.sensorType !== '') {
        if (this.searchData.sensorType == res.sensorType.toString()) {
          this.isGetSensorList = false
        } else {
          this.isGetSensorList = true
          this.initSearchData(res)
        }
      } else {
        this.isGetSensorList = true
        this.initSearchData(res)
      }
    })
    this.$nextTick(() => {
      if (this.isGetSensorList) {
        this.getName()
      }
      if (!this.searchData.cdCodes.length) {
        this.showTitle = true
        this.showechartEmpty = true
        this.$refs.uToast.show({
          title: '请选择传感器',
          type: 'warning'
        })
      }
    })
  },
  onUnload() {
    // 清除监听keyword
    uni.$off('handClickrealTimeScreen')
  },
}
</script>

<style lang="scss">
.history {
  padding: $uni-page-padding;
  &-search {
    flex: none;
  }
  .navbar-right {
    margin-right: 40rpx;
    &--icon {
      width: 40rpx;
      height: 40rpx;
    }
  }
}
/* 搜索框 */
.search {
  padding: 20rpx 28rpx;
}
.charts-box {
  display: flex;
  position: relative;
  align-items: center;
  /* transform: rotate(90deg); */
  width: 100%;
  height: 100%;
}
.popup-content {
  padding: 24rpx;
  text-align: center;
  .checkbox {
    &-item {
      height: 100rpx;
    }
    /deep/.u-checkbox-group {
      display: inline;
      .u-checkbox {
        border-bottom: 1px solid #dddddd;
        justify-content: space-between;
        flex-flow: row-reverse;
        .u-checkbox__icon-wrap {
          background: rgba(1, 72, 51, 0.2);
          border: none;
        }
      }
    }
  }
}
.chart-title {
  position: absolute;
  right: -310rpx;
  width: 770rpx;
  text-align: center;
  transform: rotate(90deg);
  display: flex;
  justify-content: center;
  .warn-box {
    height: 20rpx;
    width: 40rpx;
    background: #ef585c;
  }
  .calibration-box {
    height: 20rpx;
    width: 40rpx;
    background: #73ea5e;
  }
}
.chart-sub-title {
  position: absolute;
  right: -310rpx;
  top: 80rpx;
  width: 770rpx;
  text-align: center;
  transform: rotate(90deg);
  display: flex;
  justify-content: center;
}
</style>
